﻿using System;

namespace Sencha.Serialization.Bson.Serializers
{
	public class BsonDateTimeSerializer : TypeSerializer<BsonDateTime>
	{
		public override BsonDateTime Deserialize(IJsonReader reader)
		{
			if (reader == null)
				throw new ArgumentNullException("reader");

			if (reader is IBsonReader)
				return this.DeserializeBson(reader as IBsonReader);

			reader.ReadObjectBegin();
			var timeStampString = reader.ReadMember<string>("$date");
			reader.ReadObjectEnd(false);

			var dataTimeValue = long.Parse(timeStampString);
			var value = new BsonDateTime(dataTimeValue);
			return value;
		}
		private BsonDateTime DeserializeBson(IBsonReader reader)
		{
			if (reader.Token != BsonToken.DateTime)
				throw new Exceptions.UnexpectedBsonToken(reader, BsonToken.DateTime);

			var objectId = (BsonDateTime)reader.RawValue;
			return objectId;
		}
		public override void Serialize(IJsonWriter writer, BsonDateTime value)
		{
			if (writer == null)
				throw new ArgumentNullException("writer");

			if (writer is IBsonWriter)
			{
				this.SerializeBson(writer as IBsonWriter, value);
				return;
			}

			writer.WriteObjectBegin();
			writer.WriteMember<long>("$date", value.Raw);
			writer.WriteObjectEnd();
		}
		private void SerializeBson(IBsonWriter writer, BsonDateTime value)
		{
			writer.Write(BsonToken.DateTime, value);
		}
	}
}
